<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            div {
                width: 200px;
                height: 200px;
                background-color: olivedrab;
                /* margin: 0 auto; */
                transform: translate(0px, 0px);
                /* touch-action: none; */
                /* position: relative; */
            }
        </style>
    </head>
    <body>
        <div></div>
    </body>
    <script>
        function move() {
            // 定义鼠标点击和移动后的坐标预值
            const Mousestart = {
                x: 0,
                y: 0,
            };
            const movelength = {
                x: 0,
                y: 0,
            };
            // 元素初始位置
            const ElemStar={
                x:0,
                y:0,
            }
            // 获取元素对象
            var div1 = document.querySelector("div");
            // 触摸事件
            div1.ontouchstart = function (ev) {
                const touch1 = ev.targetTouches[0];
                Mousestart.x = touch1.pageX;
                Mousestart.y = touch1.pageY;
                // console.log(start.x, start.y);
            };
            //移动距离
            div1.ontouchmove = function (ev) {
                const touch2 = ev.targetTouches[0];
                movelength.x = ElemStar.x+touch2.pageX - Mousestart.x;
                movelength.y = ElemStar.y+touch2.pageY - Mousestart.y;
                // console.log(movelength.x, movelength.y);
                div1.style.transform = `translate(${movelength.x}px,${movelength.y}px)`;
            };
            // 结束触摸事件时，记录本次相对移动的横向、纵向距离，方便下次移动时，让他的初始位置从上次结束时移动的距离位置开始，避免移动时元素先归位再移动的情况
            div1.ontouchend = function (ev) {
                ElemStar.x = movelength.x;
                ElemStar.y = movelength.y;
            };
            //有手机弹框提示时触发
            div1.ontouchcancel = function (ev) {
                ElemStar.x = movelength.x;
                ElemStar.y = movelength.y;
            };
        }
        move();
    </script>
</html>
